package com.loong.life.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loong.common.enumerate.PhoneChargeStatus;
import com.loong.common.rabbitmq.consumer.BaseConsumer;
import com.loong.common.rabbitmq.dto.base.BusinessEventDto;
import com.loong.global.constant.MQConstant;
import com.loong.global.dto.PhoneChargeDTO;
import com.loong.life.common.backend.result.PhoneChargeResult;
import com.loong.life.handler.PhoneChargeHandler;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Description:
 * @Author: LiuQun
 * @Date: 2020/12/22 10:19
 */
@Slf4j
@Component
public class PhoneChargeReportConsumer extends BaseConsumer {

    @Resource
    private PhoneChargeHandler chargeHandler;

    @RabbitListener(queues = {MQConstant.BASE_PREFIX + MQConstant.QUEUE_NAME.PHONE_CHARGE + MQConstant.BASE_SUFFIX.QUEUE}, containerFactory = "defaultRabbitListener")
    public void receiveDLXEvent(Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] data = message.getBody();
        BusinessEventDto<JSONObject> eventDto = JSON.parseObject(new String(data)).toJavaObject(BusinessEventDto.class);
        PhoneChargeDTO phoneChargeDTO = eventDto.getData().toJavaObject(PhoneChargeDTO.class);
        PhoneChargeResult chargeResult = chargeHandler.findPhoneChargeRecordById(phoneChargeDTO.getId());
        if (ObjectUtils.isNotEmpty(chargeResult)) {
            //若手机充值状态还是等待付款状态，则关闭交易
            if (PhoneChargeStatus.WAIT_FOR_PAYMENT.getCode() == chargeResult.getChargeStatus()) {
                chargeHandler.foreheadClosePhoneChargeTrade(phoneChargeDTO.getId());
            }
        }
        submitAck(channel, deliveryTag);
    }

}
